<template>
  <div>
    <el-card class="box-1">
      <div slot="header"><span>{{ title }}</span></div>
      <el-form ref="form" :model="form" :rules="formRules" label-width="160px">
        <el-form-item label="新闻标题：" prop="title">
          <el-input v-model="form.title" />
        </el-form-item>
        <el-form-item label="新闻类型：" prop="articles_type_id">
          <el-cascader v-model="form.articles_type_id" :options="typeList" :props="{ multiple: true, expandTrigger: 'hover' }" clearable/>
        </el-form-item>
        <el-form-item label="发布时间：">
          <div>发布时间: {{ form['createTime'] }}</div>
          <label>自动刷新： </label>
          <el-radio-group v-model="form['auth_refresh']">
            <el-radio :label="1">开启</el-radio>
            <el-radio :label="0">关闭</el-radio>
          </el-radio-group>
          <el-input v-if="form['auth_refresh']" v-model="form['day_refresh']" size="small" type="number" style="width: 200px;margin-left: 20px;margin-top: 4px">
            <template slot="append">天自动刷新</template>
          </el-input>
        </el-form-item>
        <el-form-item label="略缩图显示模式">
          <el-radio-group v-model="form['picture_type']">
            <el-radio :label="1">大图</el-radio>
            <el-radio :label="3">三视图</el-radio>
            <el-radio :label="2">小图</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="略缩图：">
          <div class="remark">*注:为保证显示效果,请上传750px*400px的图片</div>
          <ws-upload-multiple-img v-model="form['thumb']" :path="form['thumb_url']" :limit="form['picture_type']===3?3:1"/>
        </el-form-item>
        <el-form-item label="视频封面：">
          <div class="remark">*注:为保证显示效果,请上传750px*400px的图片</div>
          <ws-upload-single-img v-model="form['video_cover']" :path="form['video_cover']?ImageUrl+form['video_cover']:''"/>
        </el-form-item>
        <el-form-item label="插入视频">
          <el-radio-group v-model="form['videoType']">
            <el-radio :label="0">视频链接</el-radio>
            <el-radio :label="1">本地上传</el-radio>
          </el-radio-group>
          <el-upload
            v-if="form['videoType']===1&&ENV==='CLOUD'"
            :http-request="upLoadTXVideo"
            action=""
            drag
            multiple>
            <i class="el-icon-upload"/>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          </el-upload>
          <ws-upload-single-file v-if="form['videoType']===1&&ENV!=='CLOUD'" v-model="form['file_url']" :path="form['file_url']" :api="videoUploadUrl" />
          <el-input v-else v-model="form['file_url']" placeholder="请把视频地址粘贴到此处"/>
        </el-form-item>
        <el-form-item label="简介：">
          <el-input v-model="form.description" type="textarea" rows="3"/>
        </el-form-item>
        <el-form-item label="文章详情">
          <ws-editor v-model="form['content']"/>
        </el-form-item>
        <el-form-item label="查看权限" prop="unit">
          <el-select v-model="form.read_power" placeholder="请选择查看权限">
            <el-option :value="0" label="全部"/>
            <el-option :value="1" label="内部"/>
            <el-option :value="2" label="外部"/>
          </el-select>
        </el-form-item>
        <el-form-item label="是否显示">
          <el-radio-group v-model="form.is_display">
            <el-radio :label="0">显示</el-radio>
            <el-radio :label="1">隐藏</el-radio>
          </el-radio-group>
        </el-form-item>
        <div style="text-align:center">
          <el-button type="primary" @click="submitForm('form')">保存</el-button>
          <el-button type="primary" @click="$router.back(-1)">取消</el-button>
        </div>
      </el-form>
    </el-card>

    <!--上传进度弹窗-->
    <el-dialog :visible.sync="videoUploadProgressVisible" :close-on-click-modal="false" :close-on-press-escape="false" :show-close="false" title="视频上传中..." width="360px" >
      <el-progress :text-inside="true" :stroke-width="26" :percentage="videoUploadProgress"/>
    </el-dialog>
  </div>
</template>

<script>
import TcVod from 'vod-js-sdk-v6';
import { $config } from 'vue-element-simple';
export default {
  data() {
    return {
      ENV: $config['ENV'],
      title: '',
      // ImageUrl: this.$store.getters.serverUrl,
      ImageUrl: '',

      // 视频上传地址
      videoUploadUrl: this.$store.getters.serverUrl + '/admin/ajax/uploadVideo',
      // 视频上传弹窗
      videoUploadProgressVisible: false,
      // 视频上传进度
      videoUploadProgress: 0,

      // 类型列表
      typeList: [],

      // 新闻详情
      form: {
        read_power: 0,
        is_display: 0,
        articles_type_id: '',
        picture_type: 1,
        videoType: 0
      },
      formRules: {
        title: [{ required: true, message: '请输入新闻标题', trigger: 'blur' }],
        articles_type_id: [{ required: true, message: '选择新闻类型', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.title = this.$route.query.title
    this.loadTypeList();
    console.log(this.config)
  },
  methods: {
    loadTypeList() {
      const url = 'lookarticles/allTypeList'
      this.$store.dispatch('GetConnect', { url }).then(res => {
        this.typeList = res.data;
        if (this.$route.query.id) {
          this.id = this.$route.query.id
          this.getNews(this.$route.query.id)
        } else {
          // this.form.articles_type_id = this.$route.query.typeId || ''
          this.form.articles_type_id = ''
        }
      }).catch(e => {
        this.$message.error(e.msg + ',请刷新或联系管理员')
      })
    },

    getNews(id) {
      const url = 'article/detail/' + id
      this.$store.dispatch('GetConnect', { url }).then(res => {
        res.data.videoType = 0;
        this.form = Object.assign({}, res.data);
        this.form.articles_type_id = JSON.parse(res.data.articles_type_id);
        this.form.thumb_url = [];
        if (res.data['thumb']) {
          const temp = res.data['thumb'].split(',')
          temp.forEach(item => {
            this.form.thumb_url.push({ id: item, url: item })
          })
        }
      }).catch(e => {
        this.$message.error(e.msg + ',请刷新或联系管理员')
      })
    },

    /**
     * 单提交方法,通过判断有没有form_id执行添加或编辑操作
     * formName: form表单中ref的值,即表单名
     */
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const data = Object.assign({}, this.form);
          data.typeid = 1;
          data.articles_type_id = JSON.stringify(data.articles_type_id);
          const url = this.id ? 'article/edit/' + this.id : 'article/create';
          this.$store.dispatch('GetConnect', { url, data }).then(res => {
            this.$message.success(res.msg);
            this.$router.back(-1);
          }).catch((err) => {
            this.$message.error(err.msg);
          })
        } else {
          this.$message.error('提交失败,请检查必填项')
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },

    // 获取上传签名的函数
    getSignature() {
      const url = 'upload/vodSign';
      return this.$store.dispatch('GetConnect', { url }).then(res => {
        return res.data.sign
      })
    },

    // 腾讯云点播上传视频
    upLoadTXVideo(file){
      const that = this;
      this.videoUploadProgressVisible = true;
      const tcVod = new TcVod({
        getSignature: this.getSignature // 前文中所述的获取上传签名的函数
      })
      const uploader = tcVod.upload({
        mediaFile: file.file // 媒体文件（视频或音频或图片），类型为 File
      })
      uploader.on('media_progress', function(info) {
        that.videoUploadProgress = Number(info.percent * 100).toFixed(2);
        console.log(info.percent) // 进度
      })
      uploader.done().then(function (doneResult) {
        // deal with doneResult
        that.videoUploadProgressVisible = false;
        that.videoUploadProgress = 0;
        that.form.file_url = doneResult.video.url;
        that.$message.success('视频上传成功~');
      }).catch(function (err) {
        console.log(err);
        this.$message.error(err);
      })
    }
  }
}
</script>

<style lang="scss" type="text/scss" scoped>
@import '../../../styles/index.scss';
.box-1 {
  max-width: 1000px;
  margin: 0 auto;
  > div span {
    font-size: 18px;
    font-weight: 600;
    padding: 0 10px;
  }
  .el-form {
    max-width: 900px;
    .title {
      font-weight: 600;
    }
    .remark {
      font-size: 13px;
      color: $textGray;
    }
    .el-cascader{
      width: 260px;
    }
    > div > .el-button {
      @extend .bg-green;
      width: 20%;
      min-width: 160px;
    }
  }
}
</style>
